//
//  PthreadRwlockDemo.m
//  OCLockDemo
//
//  Created by lianglibao on 2018/12/22.
//  Copyright © 2018年 梁立保. All rights reserved.
//

#import "PthreadRwlockDemo.h"
#import <pthread.h>

static pthread_rwlock_t _lock;

@implementation PthreadRwlockDemo

+ (void)initialize {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 初始化锁
        pthread_rwlock_init(&_lock, NULL);
    });
}

+ (void)pthreadRwlockTest {
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    
    for (int i = 0; i < 10; i++) {
        dispatch_async(queue, ^{
            [self read];
        });
        dispatch_async(queue, ^{
            [self write];
        });
    }
}

+ (void)read {
    pthread_rwlock_rdlock(&_lock);
    
    sleep(1);
    NSLog(@"%s", __func__);
    
    pthread_rwlock_unlock(&_lock);
}

+ (void)write {
    pthread_rwlock_wrlock(&_lock);
    
    sleep(1);
    NSLog(@"%s", __func__);
    
    pthread_rwlock_unlock(&_lock);
}

- (void)dealloc {
    pthread_rwlock_destroy(&_lock);
}

@end
